package com.example.demo.controller;

import com.example.demo.security.CustomUserDetails;
import com.example.demo.service.EnrollmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/enrollments")
@RequiredArgsConstructor
public class EnrollmentController {
    private final EnrollmentService enrollmentService;

    @PostMapping
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<Object> enrollCourse(
            @RequestBody EnrollRequest enrollRequest,
            @AuthenticationPrincipal CustomUserDetails userDetails) {
        Long studentId = userDetails.getId();
        return ResponseEntity.ok(enrollmentService.enrollCourse(studentId, enrollRequest));
    }

    @DeleteMapping("/{courseId}")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<Void> cancelEnrollment(
            @PathVariable Long courseId,
            @AuthenticationPrincipal CustomUserDetails userDetails) {
        Long studentId = userDetails.getId();
        enrollmentService.cancelEnrollment(studentId, courseId);
        return ResponseEntity.noContent().build();
    }
}